package com.heima.wemedia.publish;


import lombok.RequiredArgsConstructor;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import java.util.Date;

import static com.heima.wemedia.config.RabbitMQConfig.DELAYED_EXCHANGE;
import static com.heima.wemedia.config.RabbitMQConfig.DELAYED_QUEUE;

@Component
@RequiredArgsConstructor
public class WmNewsPublish {
    private final RabbitTemplate rabbitTemplate;


//将消息
    public void publishWmNews(Integer id, Date publishTime) {
        String message=id.toString();
          long delayMillis = publishTime.getTime() - System.currentTimeMillis();
          if(delayMillis<=0)throw new IllegalStateException("发布时间必须晚于当前时间");
        //将消息和延迟时间添加到消息队列
        rabbitTemplate.convertAndSend(DELAYED_EXCHANGE, DELAYED_QUEUE, message, new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                message.getMessageProperties().setDelay((int) delayMillis);
                return message;
            }
        });
    }
}
